package com.cee.admin.common;

import com.cee.cache.redis.RedisUtils;
import com.cee.common.exception.GlobalException;
import com.cee.common.web.result.ResultCode;
import com.cee.domain.modules.sys.entity.SysFrontUser;
import com.cee.ds.common.utils.BasePrincipalUtils;
import com.cee.ds.modules.prod.service.IProdProductDataReportService;
import com.cee.ds.modules.prod.service.IProdProductService;
import com.cee.ds.modules.sys.service.ISysFrontUserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * @author wsz
 * @since 2024/6/27
 */
public abstract class BaseProdController extends BaseController {

    @Autowired
    protected IProdProductService productService;

    @Autowired
    private IProdProductDataReportService reportService;

    @Autowired
    protected ISysFrontUserService frontUserService;

    @Autowired
    protected RedisUtils redisUtils;

    protected void checkProductPermWithCity(Long productId) {
        Integer cityId = BasePrincipalUtils.currentUser().getCityId();
        if (cityId == null) {
            return;
        }
        String cacheKey = "prod:owner:" + productId;
        Long belongUser;
        Object belongUserObj = redisUtils.get(cacheKey);
        if (belongUserObj != null) {
            belongUser = Long.valueOf(belongUserObj.toString());
        } else {
            belongUser = productService.getByIdOrEx(productId).getBelongUser();
            redisUtils.set(cacheKey, belongUser, 300);
        }
        SysFrontUser frontUser = frontUserService.getByIdOrEx(belongUser);
        if (!Objects.equals(frontUser.getCityId(), cityId)) {
            throw new GlobalException(ResultCode.NOT_PERMISSION);
        }
    }

    protected void checkReportPermWithCity(Long reportId) {
        Integer cityId = BasePrincipalUtils.currentUser().getCityId();
        if (cityId == null) {
            return;
        }
        String cacheKey = "prod:report:owner:" + reportId;
        Long belongUser;
        Object belongUserObj = redisUtils.get(cacheKey);
        if (belongUserObj != null) {
            belongUser = Long.valueOf(belongUserObj.toString());
        } else {
            belongUser = reportService.getByIdOrEx(reportId).getBelongUser();
            redisUtils.set(cacheKey, belongUser, 300);
        }
        SysFrontUser frontUser = frontUserService.getByIdOrEx(belongUser);
        if (!Objects.equals(frontUser.getCityId(), cityId)) {
            throw new GlobalException(ResultCode.NOT_PERMISSION);
        }
    }
}
